package net.xumf.support.utils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串模版类
 */
public class StringTemplate {

    /**
     * 模版解析
     * @param template 字符串模版
     * @param params 参数
     * @return 解析后的字符串串
     */
    public static String process(String template, Map<String, Object> params) {
        if (params == null || params.isEmpty()) return template;
        StringBuffer sb = new StringBuffer();
        Matcher matcher = Pattern.compile("\\$\\{\\w+}").matcher(template);
        while (matcher.find()) {
            String param = matcher.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            matcher.appendReplacement(sb, value == null ? "" : value.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
